package n1451;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	static class Node{
		Node next[]=new Node[26];
		int p;
	}
	
	static void insert(Node root,String word,int p)
	{
		Node cur=root;
		for(int i=0;i<word.length();i++)
		{
			if(cur.next[word.charAt(i)-'a']==null)
			{
				Node tmp=new Node();
				tmp.p=p;
				cur.next[word.charAt(i)-'a']=tmp;
				cur=tmp;
			}else{
				cur.next[word.charAt(i)-'a'].p+=p;
				cur=cur.next[word.charAt(i)-'a'];
			}
		}
	}
	
	static int lastlen,curlen;
	
	static Node lastnode[]=new Node[1001];
	static String[] laststr=new String[1001];
	static Node curnode[]=new Node[1001];
	static String[] curstr=new String[1001];
	
	static char[][] base={
		{'a','b','c'},
		{'d','e','f'},
		{'g','h','i'},
		{'j','k','l'},
		{'m','n','o'},
		{'p','q','r','s'},
		{'t','u','v'},
		{'w','x','y','z'},
	};
	
	static void solve(Node root,String decimal)
	{
		curnode[0]=root;
		curlen=1;
		curstr[0]="";
		for(int i=0;i<decimal.length()-1;i++)
		{
			//copy
			for(int j=0;j<curlen;j++)
			{
				lastnode[j]=curnode[j];
				laststr[j]=curstr[j];
			}
			lastlen=curlen;
			curlen=0;
			
			int d=decimal.charAt(i)-'0';
			String ans=null;
			int maxp=-1;
			for(int  j=0;j<lastlen;j++)
			{
				Node tmp=lastnode[j];
				for(int k=0;k<base[d-2].length;k++)
				{
					char cc=base[d-2][k];
					if(tmp.next[cc-'a']!=null)
					{
						curnode[curlen]=tmp.next[cc-'a'];
						curstr[curlen]=laststr[j]+cc;
						curlen++;
						if(maxp<tmp.next[cc-'a'].p)
						{
							ans=laststr[j]+cc;
							maxp=tmp.next[cc-'a'].p;
						}else if(maxp==tmp.next[cc-'a'].p&&ans.compareTo(laststr[j]+cc)>0)
						{
							ans=laststr[j]+cc;
						}
					}
				}
			}
			System.out.println(ans==null?"MANUALLY":ans);
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{

		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		int t=Integer.parseInt(bf.readLine());
		for(int i=0;i<t;i++)
		{
			System.out.println("Scenario #"+(i+1)+":");
			int w=Integer.parseInt(bf.readLine());
			Node root=new Node();
			for(int j=0;j<w;j++)
			{
				StringTokenizer st=new StringTokenizer(bf.readLine());
				String word=st.nextToken();
				int p=Integer.parseInt(st.nextToken());
				insert(root,word,p);
			}
			int q=Integer.parseInt(bf.readLine());
			for(int j=0;j<q;j++)
			{
				solve(root,bf.readLine());
				System.out.println();
			}
			System.out.println();
		}
	}

}
